﻿using Nest;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class MustBaseSpecification<T> : ISearchSpecification<ISearchRequest<T>> where T : class
    {
        private readonly IEnumerable<ISearchSpecification<ISearchRequest<T>>> _queries;

        public MustBaseSpecification(IEnumerable<ISearchSpecification<ISearchRequest<T>>> queries)
            => _queries = queries ?? throw new ArgumentNullException($"{nameof(queries)} cannot be null.");

        public ISearchRequest<T> IsSatisfiedBy()
        {
            return new SearchDescriptor<T>()
                .Query(q => q
                    .Bool(b => b
                        .Must(
                            _queries.Select(qu => qu
                                .IsSatisfiedBy()
                                .Query
                            ).ToArray()
                        )
                    )
                );
        }
    }
}